package com.acwing.lc.part1;

import java.util.Arrays;

/**
 * @author rkc
 * @date 2022/9/9 16:03
 */
public class LC16最接近的三数之和 {

    public int threeSumClosest(int[] nums, int target) {
        int ans = 20010;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1, k = nums.length - 1; j < k; j++) {
                while (j < k - 1 && nums[i] + nums[j] + nums[k - 1] >= target) k--;
                int val = nums[i] + nums[j] + nums[k];
                if (Math.abs(val - target) < Math.abs(ans - target)) {
                    ans = val;
                }
                if (j < k - 1) {
                    val = nums[i] + nums[j] + nums[k - 1];
                    if (Math.abs(val - target) < Math.abs(ans - target)) {
                        ans = val;
                    }
                }
            }
        }
        return ans;
    }
}
